var express = require('express');
var visitRouter = express.Router();
let SQLQuery = require('../utils/query.js');

visitRouter.post('/client/createVisit', async function (req, res) {
    try {
        let queryObj = req.body;
        var addSql = 'insert into visit(pageName,ipAdress,adress,createTime) values(?,?,?,?)';
        let IP = req.headers['x-forwarded-for'] ? req.headers['x-forwarded-for'].split(',').pop().trim() : '0.0.0.0';

        let adress = await this.common.getIPAdress(IP)

        var addSqlParams = [queryObj.pageName, IP, adress.data.prov + adress.data.city === NaN ? '' : adress.data.prov + adress.data.city, new Date()];

        let result = await SQLQuery.query(addSql, addSqlParams);
        res.send(global.common.resJson(0, '添加成功！', result));
    } catch (err) {
        res.send(err)
    }
})

visitRouter.post('/client/visitList', async function (req, res) {
    try {
        res.send(global.common.resJson(0, '成功！', await SQLQuery.query(`SELECT * FROM visit WHERE DATE(createTime) = CURDATE();`, null)));
    } catch (err) {
        res.send(err)
    }
})

visitRouter.post('/client/weather', async function (req, res) {
    try {
        let queryObj = req.body;
        res.send(global.common.resJson(0, '成功！', await this.common.getWeather(queryObj.code)));
    } catch (err) {
        res.send(err)
    }
})

visitRouter.post('/getPanelData', async function (req, res) {
    try {
        let visitLog = await SQLQuery.query(`SELECT * FROM visit WHERE DATE(createTime) = CURDATE();`, null);
        let visitLogAll = await SQLQuery.query(`SELECT * FROM visit;`, null);
        let dailyVisit = await SQLQuery.query(`SELECT DISTINCT ipAdress FROM visit WHERE DATE(createTime) = CURDATE();`, null);
        let allVisit = await SQLQuery.query(`SELECT DISTINCT ipAdress FROM visit;`, null);

        let data = {
            pv: visitLog.length,
            totalPv: visitLogAll.length,
            uv: dailyVisit.length,
            totalUv: allVisit.length
        }
        res.send(global.common.resJson(0, '成功！', data));
    } catch (err) {
        res.send(err)
    }
})


module.exports = visitRouter;